import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input, message } from 'antd';
import './Denglu.css';
import imageSrc from '../../picture/tubiao.png';
import chaocai from '../../picture/chaocai1.gif';
import { useState,useEffect } from 'react';
import Password from 'antd/es/input/Password';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';       

import { useContext } from 'react';  
import { UploadContext } from '../uploadContext'; // 导入UploadContext 

const Denglu = () => {
  const nav = useNavigate();
  const [inputValue1, setInputValue1] = useState('');
  const [inputValue2, setInputValue2] = useState('');
  const { setUser } = useContext(UploadContext);  

  const handleChange1 = (event) => {
    setInputValue1(event.target.value);
  };
  const handleChange2 = (event) => {
    setInputValue2(event.target.value);
  };
  const handleSubmit = (event) => {
    console.log('输入的值：', inputValue1, inputValue2);
    const postData = {
      user_name: inputValue1,
      password: inputValue2
    };
    axios({
      method: 'post',
      url: 'http://localhost:3001/own/debark',
      data: postData,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded', 
      }
    })
    .then(response => {  
      console.log(response.data.user);  
      if (response.data.success) { // 修改这里  
        // 假设 response.data.user 包含用户信息，如邮箱或昵称  
        const user = response.data.user; // 假设后端返回了用户信息  
        // 使用从 UploadContext 中获取的 setUser 方法来更新用户信息  
        setUser(user); // 这里需要确保 setUser 是在 UploadContext 的 Consumer 中或通过 useContext Hook 获得的  
        localStorage.setItem('user', JSON.stringify(user)); // 保存用户信息到本地存储
        nav('/');  
      } else {  
        message.error(response.data.message || '账号或密码错误！'); // 修改这里  
      }  
    })  
    .catch(error => {  
      console.error('There was an error!', error);  
      message.error('账号或密码错误！');  
    });
  };

  useEffect(() => {  
    const storedUser = localStorage.getItem('user');  
    if (storedUser) {  
      try {  
        const user = JSON.parse(storedUser);  
        // 如果用户信息存在，你可以选择自动登录或做其他处理  
        // 例如，使用setUser更新Context中的用户信息，并跳转到主页  
        setUser(user);  
        nav('/');  
      } catch (error) {  
        // 处理JSON解析错误  
        console.error('Error parsing user from localStorage:', error);  
        // 清除localStorage中的用户信息（可选）  
        localStorage.removeItem('user');  
      }  
    }  
  }, []);



  return (
    <div className='zong'>
      <div className='title'>
        <img src={imageSrc} alt="Description of the image" className='image' />
        <div>
          <text className='title-text'>佳肴绘卷</text>
        </div>
      </div>
      <div className="centered-form">
        <div className="form-container">
          <div className="image-container">
            <img src={imageSrc} alt="Logo" className="logo-image" />
          </div>
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{
              remember: true,
            }}
            // onFinish={onFinish}
            onFinish={handleSubmit}
          >
            <div className='zi'>
              <text className='zi1'>登录</text>
              <text className='zi2' onClick={()=>nav('/zhuce')}>还没有账号？去注册</text>
            </div>
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: '请输入你的邮箱或昵称',
                },
              ]}
            >
              <div className="input-wrapper">
                <div className="account-label">账 号</div>
                <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入邮箱或昵称"
                  className="account-input" onChange={handleChange1} value={inputValue1} />
              </div>
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入你的密码',
                },
              ]}
            >
              <div className="input-wrapper1">
                <div className="account-label1">密 码</div>
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="请输入密码"
                  className="account-input"
                  onChange={handleChange2} value={inputValue2}
                />
              </div>
            </Form.Item>
            

            <Form.Item>
              <div className="input-wrapper2">
                <Button type="primary" htmlType="submit" className="login-form-button">
                  登录
                </Button>
              </div>
              {/* Or <a href="">register now!</a> */}
            </Form.Item>
            <Form.Item>
              <div className="additional-options">
                <a href="#" onClick={() => nav('/houdeng')}>管理员登录</a>
                <a href="#">忘记密码</a>
              </div>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};
export default Denglu;
